package com.xoa.service.inv;

import com.xoa.dao.crm.SupplierMapper;
import com.xoa.dao.inv.InvWarehouseMapper;
import com.xoa.dao.inv.PoCommodityEnterMapper;
import com.xoa.dao.inv.ProductTypeMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.Supplier;
import com.xoa.model.inv.InvWarehouse;
import com.xoa.model.inv.OmShipment;
import com.xoa.model.inv.PoCommodityEnter;
import com.xoa.model.inv.ProductType;
import com.xoa.model.users.Users;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormatUtils;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.omg.PortableServer.POA;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PoCommodityEnterService {

    @Resource
    private PoCommodityEnterMapper poCommodityEnterMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private InvWarehouseMapper invWarehouseMapper;

    public ToJson<PoCommodityEnter> insertProduct(HttpServletRequest request, PoCommodityEnter poCommodityEnter) {
        ToJson<PoCommodityEnter> toJson =new ToJson<PoCommodityEnter>(1,"err");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        try {
            //处理前台传过来的时间
            //poCommodityEnter.setEnterIndate(DateFormatUtils.parse(poCommodityEnter.getEnterIndates()));
            //生成单据号
            Date date = new Date();//当前日期---生成单据号的主要因素
            DateFormat format=new SimpleDateFormat("yyyyMMdd");
            String timeStr=format.format(date);
            String stt = "NO";//固定前缀
            int newNumber = 00001;//自增编号
            String documentNo = "";
            if(poCommodityEnter!=null){
                List<PoCommodityEnter> list = poCommodityEnterMapper.selectProductInfoAll();
                if(list.size()>0&&list!=null){
                    if (list.get(0).getDocumentNo() != null && !list.get(0).getDocumentNo().isEmpty()) {
                        String str = list.get(0).getDocumentNo().substring(10);
                        int newNo = Integer.parseInt(str) + 1;
                        String dtr = String.format("%05d", newNo);
                        documentNo = stt + timeStr + dtr;
                    }
                    poCommodityEnter.setDocumentNo(documentNo);
                }else {
                    String dtr = String.format("%05d", newNumber);
                    documentNo =stt + timeStr + dtr;
                    poCommodityEnter.setDocumentNo(documentNo);
                }

            }
            //入库人
            if(poCommodityEnter.getUserId()!=null){
                poCommodityEnter.setUserId(poCommodityEnter.getUserId());
            }else {
                poCommodityEnter.setUserId(users.getUserId());
            }
            int count=poCommodityEnterMapper.insertSelective(poCommodityEnter);
            if(count>0){
                toJson.setObject(poCommodityEnter);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityEnter> updateProduct(HttpServletRequest request, PoCommodityEnter poCommodityEnter) {
        ToJson<PoCommodityEnter> toJson =new ToJson<PoCommodityEnter>(1,"err");
        try {
            int count=poCommodityEnterMapper.updateByPrimaryKeySelective(poCommodityEnter);
            if(count>0){
                toJson.setObject(poCommodityEnter);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityEnter> selectProductById(HttpServletRequest request, Integer enterId) {
        ToJson<PoCommodityEnter> toJson =new ToJson<PoCommodityEnter>(1,"err");
        try {
            PoCommodityEnter poCommodityEnter=poCommodityEnterMapper.selectByPrimaryKey(enterId);

            if(poCommodityEnter!=null){
                //商品大类名称
                if(!StringUtils.checkNull(poCommodityEnter.getProductType())&&poCommodityEnter.getProductType()!=""){
                    ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poCommodityEnter.getProductType()));
                    if(productType!=null){
                        poCommodityEnter.setProductTypeName(productType.getProductTypeName());
                    }
                }
                //供应商名称
                if(poCommodityEnter.getSupplierId()!=0&&poCommodityEnter.getSupplierId()!=null){
                    Supplier supplier = supplierMapper.selectByPrimaryKey(poCommodityEnter.getSupplierId());
                    if(supplier!=null){
                        poCommodityEnter.setSupplierName(supplier.getSupplierName());
                    }
                }
                //入库人名称
                if(poCommodityEnter.getUserId()!=""&&poCommodityEnter.getUserId()!=null){
                    Users users = usersMapper.getUserId(poCommodityEnter.getUserId());
                    if(users!=null){
                        poCommodityEnter.setUserName(users.getUserName());
                    }
                }
                //仓库名称
                if(poCommodityEnter.getWarehouseId()!=0&&poCommodityEnter.getWarehouseId()!=null){
                    InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(poCommodityEnter.getWarehouseId());
                    if(invWarehouse!=null){
                        poCommodityEnter.setWarehouseName(invWarehouse.getWarehouseName());
                    }
                }
            }
            if(poCommodityEnter!=null){
                toJson.setObject(poCommodityEnter);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityEnter> deleteProductById(HttpServletRequest request, Integer enterId) {
        ToJson<PoCommodityEnter> toJson =new ToJson<PoCommodityEnter>(1,"err");
        try {
            poCommodityEnterMapper.deleteByPrimaryKey(enterId);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityEnter> selectProductInfo(HttpServletRequest request, PoCommodityEnter poCommodityEnter,Integer type,Integer isArrears,Integer page,Integer limit) {
        ToJson<PoCommodityEnter> toJson =new ToJson<PoCommodityEnter>(1,"err");
        Map<String, Object> map=new HashMap<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setUseFlag(true);
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            map.put("pageParams",pageParams);
        }catch (Exception e){
            e.getMessage();
        }
        try {
            map.put("obj",poCommodityEnter);
            map.put("type",type);//按照日期查询 type=1按日查 type=2按月查 type=3按年查
            map.put("isArrears", isArrears);
            List<PoCommodityEnter> list=poCommodityEnterMapper.selectProductInfo(map);
            if(list!=null&&list.size()>0){
                for(int i=0;i<list.size();i++){
                    //商品大类名称
                    if(!StringUtils.checkNull(list.get(i).getProductType())&&list.get(i).getProductType()!=""){
                        ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(list.get(i).getProductType()));
                        if(productType!=null){
                            list.get(i).setProductTypeName(productType.getProductTypeName());
                        }
                    }
                    //供应商名称
                    if(list.get(i).getSupplierId()!=0&&list.get(i).getSupplierId()!=null){
                        Supplier supplier = supplierMapper.selectByPrimaryKey(list.get(i).getSupplierId());
                        if(supplier!=null){
                            list.get(i).setSupplierName(supplier.getSupplierName());
                        }
                    }
                    //入库人名称
                    if(list.get(i).getUserId()!=""&&list.get(i).getUserId()!=null){
                        Users users = usersMapper.getUserId(list.get(i).getUserId());
                        if(users!=null){
                            list.get(i).setUserName(users.getUserName());
                        }
                    }
                    //仓库名称
                    if(list.get(i).getWarehouseId()!=null && list.get(i).getWarehouseId()!=0){
                        InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(list.get(i).getWarehouseId());
                        if(invWarehouse!=null){
                            list.get(i).setWarehouseName(invWarehouse.getWarehouseName());
                        }
                    }
                    //进货人名称
                    if(list.get(i).getUserId()!=null&&list.get(i).getUserId()!=""){
                        /*String substring = list.get(i).getUserId().substring(0,list.get(i).getUserId().indexOf(","));
                        list.get(i).setUserName(usersMapper.findUsersByuserId(substring).getUserName());*/

                        String[] split = list.get(i).getUserId().split(",");
                        List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByUids) {
                            sb.append(u.getUserName() + ",");
                        }
                        list.get(i).setUserName(sb.toString());
                    }

                }
                toJson.setObj(list);
                PageParams pageParams=(PageParams)map.get("pageParams");
                toJson.setTotleNum(pageParams.getTotal());
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }
    //查询所有出货人
    public ToJson<PoCommodityEnter> selectUsers() {
        ToJson<PoCommodityEnter> json = new ToJson(1,"err");
        try {
            List list=new ArrayList();
            List<PoCommodityEnter> poCommodityEnters = poCommodityEnterMapper.selectUsers();
            String str="";
            for (PoCommodityEnter user : poCommodityEnters) {
                str+=user.getUserId();
            }
            String[] split = str.split(",");
            for (String s:split) {
                PoCommodityEnter poCommodityEnter=new PoCommodityEnter();
                poCommodityEnter.setUserId(s);
                poCommodityEnter.setUserName(usersMapper.findUsersByuserId(s).getUserName());
                list.add(poCommodityEnter);
            }

            json.setMsg("ok");
            json.setFlag(0);
            json.setObj(list);
        }catch (Exception e){
            json.setMsg(e.getMessage());
        }

        return json;
    }
    /**
     * 查询所有欠款供货商
     */
    public List<PoCommodityEnter> selectSupplier(String supplierName) {
        PoCommodityEnter poCommodityEnter = new PoCommodityEnter();
        poCommodityEnter.setSupplierName(supplierName);
        List<PoCommodityEnter> poCommodityEnters = poCommodityEnterMapper.selectSupplierId(poCommodityEnter);
        if (supplierName == null || supplierName == "") {
            for (PoCommodityEnter pce : poCommodityEnters
            ) {
                pce.setSupplierName(supplierMapper.selectByPrimaryKey(pce.getSupplierId()).getSupplierName());
            }
        }
        if (poCommodityEnters != null) {
            return poCommodityEnters;
        } else {
            return null;
        }

    }

    /**
     * 商品库存
     * @param request
     * @param poCommodityEnter
     * @param page
     * @param limit
     * @return
     */
    public ToJson seleceStock(HttpServletRequest request, PoCommodityEnter poCommodityEnter, Integer page, Integer limit) {
        ToJson toJson=new ToJson(1,"err");
        Map map=new HashMap();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(true);
            map.put("pageParams",pageParams);
        }catch (Exception e){
            e.getMessage();
        }
        try {
            //要查询的仓库
            map.put("warehouseId",poCommodityEnter.getWarehouseId());

            map.put("enterIndates",poCommodityEnter.getEnterIndates()); //时间
            map.put("enterIndate",poCommodityEnter.getEnterIndate());

            //商品内容
            map.put("productType",poCommodityEnter.getProductType());
            map.put("enterName",poCommodityEnter.getEnterName());
            map.put("enterSpecs",poCommodityEnter.getEnterSpecs());
            map.put("enterCode",poCommodityEnter.getEnterCode());



            //人员
            map.put("supplierId",poCommodityEnter.getSupplierId());
            map.put("userId",poCommodityEnter.getUserId());

            //入库单价
            map.put("enterInPrice",poCommodityEnter.getEnterInprice());


            //库存
            map.put("enterNum",poCommodityEnter.getEnterNum());



            List<PoCommodityEnter> list=poCommodityEnterMapper.selectSumProductInfo(map);
            for(PoCommodityEnter poEnter:list) {

                //商品大类名称
                if(!StringUtils.checkNull(poEnter.getProductType())){
                    ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poEnter.getProductType()));
                    if(productType!=null){
                        poEnter.setProductTypeName(productType.getProductTypeName());
                    }
                }



                Map pomap=new HashMap(); //统计出的数据

                Map map1=new HashMap(); //统计的条件

                //进货统计
                //仓库进货数
                pomap.put("Enter_Purchase",poEnter.getEnterNum());


                //仓库各月进货数,指定的商品+时间范围
                map1.put("SField","ENTER_NUM"); //要统计的字段
                map1.put("table","po_commodity_enter"); //要查询的表

                //指定的商品编码
                map1.put("Field2","ENTER_ID"); //要查询的条件字段
                map1.put("condition2",poEnter.getEnterId()); //要查询的条件值
                map1.put("FieldTime","ENTER_INDATE"); //要查询的条件字段
                map1.put("conditionTime",poCommodityEnter.getEnterIndates()); //要查询的条件值
                Map map2 = poCommodityEnterMapper.fundSumMonth(map1);
                pomap.put("Enter_month_Purchase",map2.get("sum"));

                map1.clear();
                //销售统计
                //仓库出货数，指定的商品+商品所在的库
                map1.put("SField","SHIPMENT_NUM"); //要统计的字段
                map1.put("table","om_shipment"); //要查询的表
                //指定的商品
                map1.put("Field","ENTER_ID"); //要查询的条件字段
                map1.put("condition",poEnter.getEnterId()); //要查询的条件值
                map1.put("Field2","WAREHOUSE_ID"); //要查询的条件字段
                map1.put("condition2",poEnter.getWarehouseId()); //要查询的条件值
                Map map3 = poCommodityEnterMapper.fundSumMonth(map1);
                pomap.put("Enter_Transfer",map3.get("sum"));

                map1.clear();
                //仓库月出货数，指定的商品+商品所在的仓库+时间范围
                map1.put("SField","SHIPMENT_NUM"); //要统计的字段
                map1.put("table","om_shipment"); //要查询的表

                map1.put("Field","ENTER_ID"); //要查询的条件字段
                map1.put("condition",poEnter.getEnterId()); //要查询的条件值
                map1.put("Field2","WAREHOUSE_ID"); //要查询的条件字段
                map1.put("condition2",poEnter.getWarehouseId()); //要查询的条件值
                map1.put("FieldTime","SHIPMENT_DATE"); //要查询的条件字段
                map1.put("conditionTime",poCommodityEnter.getEnterIndates()); //要查询的条件值
                Map map4 = poCommodityEnterMapper.fundSumMonth(map1);
                pomap.put("Enter_month_Transfer",map4.get("sum"));


                map1.clear();
                //商品进货退货数
                map1.put("SField","RETREAT_NUM"); //要统计的字段
                map1.put("table","po_commodity_out"); //要查询的表
                map1.put("Field","ENTER_ID"); //要查询的条件字段
                map1.put("condition",poEnter.getEnterId()); //要查询的条件值
                map1.put("Field2","WAREHOUSE_ID"); //要查询的条件字段
                map1.put("condition2",poEnter.getWarehouseId()); //要查询的条件值
                Map map5 = poCommodityEnterMapper.fundSumMonth(map1); //查询退货库存

                map1.clear();
                //销售退货数
                map1.put("SField","RETURN_NUM"); //要统计的字段
                map1.put("table","om_return"); //要查询的表
                map1.put("Field","ENTER_ID"); //要查询的条件字段
                map1.put("condition",poEnter.getEnterId()); //要查询的条件值
                map1.put("Field2","WAREHOUSE_ID"); //要查询的条件字段
                map1.put("condition2",poEnter.getWarehouseId()); //要查询的条件值
                Map map6 = poCommodityEnterMapper.fundSumMonth(map1); //查询退货库存


                if (poEnter.getEnterNum()==null){
                    poEnter.setEnterNum(0);
                }
                //某个仓库库存数

                //总数量 进货数-退货数-销售数+销售退货数=剩余库存
                int total=poEnter.getEnterNum()-Integer.parseInt(map5.get("sum").toString())-Integer.parseInt(map3.get("sum").toString())+Integer.parseInt(map6.get("sum").toString());
                pomap.put("Enter_total",total);

                //总仓库库存金额
                pomap.put("Enter_all_total_price",total * poEnter.getEnterInprice());

                //总仓库进货金额
                pomap.put("Enter_price",poEnter.getEnterNum()*poEnter.getEnterInprice());
                //总仓库某月进货金额
                pomap.put("Enter_price_month",Integer.parseInt(map2.get("sum").toString()) * poEnter.getEnterInprice());
                //总仓库出货金额
                pomap.put("Out_price",Integer.parseInt(map3.get("sum").toString())*poEnter.getEnterInprice());
                //总仓库某月出货金额
                pomap.put("Out_price_month",Integer.parseInt(map4.get("sum").toString())*poEnter.getEnterInprice());


                //总仓库仓库累计销售成本 (进货数-退货) * 各个商品的价格
                pomap.put("Enter_all_price",(poEnter.getEnterNum()-Integer.parseInt(map3.get("sum").toString())) * poEnter.getEnterInprice());

                //当月的销售成本 = (当月进货数-当月的出货数)*商品的价格
                double Enter_all_price_month= (Integer.parseInt(map2.get("sum").toString())  - Integer.parseInt(map4.get("sum").toString())) * poEnter.getEnterInprice();
                pomap.put("Enter_all_price_month",Enter_all_price_month);

                //所有仓库的数量，所有仓库的进货数-所有仓库的退货数-所有仓库的销售数+所有仓库销售的退货数=所有仓库的库存（这个商品在所有仓库的库存）
                pomap.put("Enter_all_total",poCommodityEnterMapper.findEnterAllTotal(poEnter.getEnterId()));

                poEnter.setMap(pomap);

            }

            toJson.setMsg("ok");
            toJson.setFlag(0);
            toJson.setTotleNum(list.size());
            toJson.setObj(list);

        }catch (Exception e){
            e.getMessage();
        }
        return toJson;
    }
}
